//
//  NotificationService.m
//  NotificationServiceExtension
//
//  Created by lx on 2024/4/2.
//

#import "NotificationService.h"
#import <OneSignalExtension/OneSignalExtension.h>
#import <Intents/Intents.h>
#import <SDWebImage.h>
#import <MJExtension.h>



@interface NotificationService ()


@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@property (nonatomic, strong) UNNotificationRequest *receivedRequest;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    NSLog(@"%s, content = %@, userInfo = %@", __func__, request.content, request.content.userInfo);
    self.receivedRequest = request;
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    [self setSendMessageIntentWithContent:request.content];
}

- (void)contentHandlerComplete {
    [OneSignalExtension didReceiveNotificationExtensionRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent withContentHandler:self.contentHandler];
}

- (void)serviceExtensionTimeWillExpire {
    [OneSignalExtension serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
    self.contentHandler(self.bestAttemptContent);
}

- (void)setSendMessageIntentWithContent:(UNNotificationContent *)content {
    
    if (@available(iOS 15.0, *)) {
        
        NSDictionary *custom = content.userInfo[@"custom"][@"a"];
        NSString *senderImageURLString = custom[@"large_icon"];
        NSString *title = content.title;
        NSString *subtitle = content.subtitle;
        NSString *body = content.body;
        
        [self downloadImageWithURLString:senderImageURLString completionHandle:^(UIImage *image) {
            if (image) {
                
                INImage *avatar = [INImage imageWithImageData:UIImagePNGRepresentation(image)];;
                
                INPersonHandle *messageSenderPersonHandle = [[INPersonHandle alloc] initWithValue:@"" type:INPersonHandleTypeUnknown];
                NSPersonNameComponents *components = [[NSPersonNameComponents alloc] init];
                INPerson *messageSender = [[INPerson alloc] initWithPersonHandle:messageSenderPersonHandle nameComponents:components
                                                                     displayName:title image:avatar contactIdentifier:nil customIdentifier:nil
                                                                            isMe:NO suggestionType:INPersonSuggestionTypeNone];
                // 创建自己对象
                
                // 创建intent
                INSpeakableString *speakableString = [[INSpeakableString alloc] initWithSpokenPhrase:subtitle.length ? subtitle : @""];
                INSendMessageIntent *intent = [[INSendMessageIntent alloc] initWithRecipients:@[messageSender]
                                                                          outgoingMessageType:INOutgoingMessageTypeOutgoingMessageText
                                                                                      content:body speakableGroupName:speakableString
                                                                       conversationIdentifier:nil serviceName:nil sender:messageSender attachments:nil];
                
                [intent setImage:avatar forParameterNamed:@"speakableGroupName"];
                // 创建 interaction
                INInteraction *interaction = [[INInteraction alloc] initWithIntent:intent response:nil];
                interaction.direction = INInteractionDirectionIncoming;
                [interaction donateInteractionWithCompletion:nil];
                // 创建 处理后的 UNNotificationContent
                NSError *error = nil;
                UNNotificationContent *messageContent = [content contentByUpdatingWithProvider:intent error:&error];
                if (!error && messageContent) {
                    self.bestAttemptContent = [messageContent mutableCopy];
                    [self contentHandlerComplete];
                } else {
                    [self contentHandlerComplete];
                }
            } else {
                [self contentHandlerComplete];
            }
        }];
    } else {
        [self contentHandlerComplete];
    }
}

- (void)downloadImageWithURLString:(NSString *)url completionHandle:(void(^)(UIImage * _Nullable image))completionHandler {
    if (![url isKindOfClass:NSString.class]) {
        completionHandler(nil);
        return;
    }
    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:url] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        NSLog(@"image = %@, data = %@, cacheType = %ld", image, data, cacheType);
        completionHandler(image);
    }];
}


@end
